/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.material.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.library.entity.QuestionBankEntity;
import org.springblade.modules.library.entity.QuestionOptionEntity;
import org.springblade.modules.library.service.IQuestionBankService;
import org.springblade.modules.library.service.IQuestionOptionService;
import org.springblade.modules.library.vo.QuestionBankVO;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.material.entity.WrongQuestionEntity;
import org.springblade.modules.material.vo.WrongQuestionVO;
import org.springblade.modules.material.excel.WrongQuestionExcel;
import org.springblade.modules.material.wrapper.WrongQuestionWrapper;
import org.springblade.modules.material.service.IWrongQuestionService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.tool.constant.BladeConstant;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户错题表 控制器
 *
 * @author junxin
 * @since 2024-04-16
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-wrongQuestion/wrongQuestion")
@Api(value = "用户错题表", tags = "用户错题表接口")
public class WrongQuestionController extends BladeController {

	private final IWrongQuestionService wrongQuestionService;
	private final IQuestionBankService questionBankService;
	private final IQuestionOptionService questionOptionService;

	/**
	 * 用户错题表 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入wrongQuestion")
	public R<WrongQuestionVO> detail(WrongQuestionEntity wrongQuestion) {
		WrongQuestionEntity detail = wrongQuestionService.getOne(Condition.getQueryWrapper(wrongQuestion));
		return R.data(WrongQuestionWrapper.build().entityVO(detail));
	}

	/**
	 * 用户错题表 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "用户错题分页", notes = "传入wrongQuestion")
	public R<IPage<WrongQuestionVO>> list(@ApiIgnore @RequestParam Map<String, Object> wrongQuestion, Query query) {
		QueryWrapper<WrongQuestionEntity> queryWrapper = Condition.getQueryWrapper(wrongQuestion, WrongQuestionEntity.class);
		queryWrapper.lambda().eq(WrongQuestionEntity::getUserId,AuthUtil.getUserId()).orderByDesc(WrongQuestionEntity::getCreateTime);

		IPage<WrongQuestionEntity> pages = wrongQuestionService.page(Condition.getPage(query), queryWrapper);
		IPage<WrongQuestionVO> wrongQuestionVOIPage = WrongQuestionWrapper.build().pageVO(pages);
		if (Func.isNotEmpty(wrongQuestionVOIPage.getRecords())) {
			//获取分页后的questionId集
			List<WrongQuestionVO> wrongQuestionList=wrongQuestionVOIPage.getRecords();
			List<Long> questionBankIds= wrongQuestionList.stream()
				.map(WrongQuestionEntity::getQuestionBankId)
				.collect(Collectors.toList());
			//获取试题集的所有选项  并根据试题id分组
			Map<Long, List<QuestionOptionEntity>> optionMap = questionOptionService.list(Wrappers.<QuestionOptionEntity>query().lambda()
				.in(QuestionOptionEntity::getQuestionBankId, questionBankIds)).stream().collect(Collectors.groupingBy(QuestionOptionEntity::getQuestionBankId));

			//给指定试题赋值选项
			wrongQuestionList.forEach(wrongQuestionVO -> {
				List<QuestionOptionEntity> questionOptionEntityList = optionMap.get(wrongQuestionVO.getQuestionBankId());
				if (CollectionUtil.isEmpty(questionOptionEntityList)) {//如果是简答题，选项有可能为空，需要默认给它提供一个选项
					questionOptionEntityList=new ArrayList<>();
					QuestionOptionEntity questionOptionEntity=new QuestionOptionEntity();
					questionOptionEntity.setQuestionBankId(wrongQuestionVO.getQuestionBankId());
					questionOptionEntityList.add(questionOptionEntity);
				}
				wrongQuestionVO.setOptionVOList(questionOptionEntityList);
			});
		}

		return R.data(wrongQuestionVOIPage);
	}



	/**
	 * 用户错题表 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增错题", notes = "传入wrongQuestion")
	public R save(@Valid @RequestBody WrongQuestionEntity wrongQuestion) {
		if (Func.isEmpty(wrongQuestion.getQuestionBankId())) throw new ServiceException("请选择要添加的题");
		Long userId = AuthUtil.getUserId();
		List<WrongQuestionEntity> oldWrongList = wrongQuestionService.list(Wrappers.<WrongQuestionEntity>query().lambda()
			.eq(WrongQuestionEntity::getUserId, userId).eq(WrongQuestionEntity::getQuestionBankId, wrongQuestion.getQuestionBankId()));
		if (Func.isNotEmpty(oldWrongList))  throw new ServiceException("此题目已添加错题集");

		QuestionBankEntity questionEntity = questionBankService.getById(wrongQuestion.getQuestionBankId());
		BeanUtil.copyProperties(questionEntity,wrongQuestion,"id");
		wrongQuestion.setUserId(userId);
		return R.status(wrongQuestionService.save(wrongQuestion));
	}

	/**
	 * 用户错题表 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入wrongQuestion")
	public R update(@Valid @RequestBody WrongQuestionEntity wrongQuestion) {
		return R.status(wrongQuestionService.updateById(wrongQuestion));
	}


	/**
	 * 用户错题表 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "移除错题", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(wrongQuestionService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 导出数据
	 */
	@GetMapping("/export-wrongQuestion")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导出数据", notes = "传入wrongQuestion")
	public void exportWrongQuestion(@ApiIgnore @RequestParam Map<String, Object> wrongQuestion, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<WrongQuestionEntity> queryWrapper = Condition.getQueryWrapper(wrongQuestion, WrongQuestionEntity.class);
		//if (!AuthUtil.isAdministrator()) {
		//	queryWrapper.lambda().eq(WrongQuestion::getTenantId, bladeUser.getTenantId());
		//}
		queryWrapper.lambda().eq(WrongQuestionEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<WrongQuestionExcel> list = wrongQuestionService.exportWrongQuestion(queryWrapper);
		ExcelUtil.export(response, "用户错题表数据" + DateUtil.time(), "用户错题表数据表", list, WrongQuestionExcel.class);
	}

}
